package com.mzlalal.repeat.submit.service;

import cn.hutool.core.collection.CollUtil;
import com.mzlalal.repeat.submit.prop.RepeatSubmitProperties;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mzlalal
 * @date 2022/7/17 0:33
 **/
@Component
public class RepeatSubmitPatternService {
    /**
     * 忽略
     */
    private final List<PathPattern> excludePatternList = new ArrayList<>();
    /**
     * 包含
     */
    private final List<PathPattern> includePatternList = new ArrayList<>();

    public RepeatSubmitPatternService(RepeatSubmitProperties properties) {
        if (CollUtil.isNotEmpty(properties.getExcludePattern())) {
            for (String exclude : properties.getExcludePattern()) {
                excludePatternList.add(new PathPatternParser().parse(exclude));
            }
        }
        if (CollUtil.isNotEmpty(properties.getIncludePattern())) {
            for (String exclude : properties.getIncludePattern()) {
                includePatternList.add(new PathPatternParser().parse(exclude));
            }
        }
    }

    /**
     * 检查请求地址是否在拦截范围之内
     *
     * @param uri 请求地址
     * @return true 放行 false 检查重复提交
     */
    public boolean checkRequestUriWithPattern(String uri) {
        // 检查是否在忽略范围内
        for (PathPattern pathPattern : excludePatternList) {
            if (pathPattern.matches(PathContainer.parsePath(uri))) {
                return true;
            }
        }
        // 检查是否在包含范围内
        for (PathPattern pathPattern : includePatternList) {
            if (pathPattern.matches(PathContainer.parsePath(uri))) {
                return false;
            }
        }
        // 放行
        return true;
    }
}
